using System.Collections;
using System.IO;
using UnityEditor;
using UnityEngine;
using Framework.Define;
using Framework.Manager;
using System.Diagnostics;

using Debug = UnityEngine.Debug;
using System.Text;

namespace FrameworkEditor.UITools.ConfigGenerate
{
    public class ConfigGenerateEditor : EditorWindow
    {
        /// <summary>配置生成目录路径（即导表工具所在路径）</summary>
        private static string mConfigGenerateFolderPath = string.Empty;
        /// <summary>配置生成客户端目录名称</summary>
        private static string mConfigGenerateClientFolderName = "Client";
        /// <summary>配置生成Exe名称</summary>
        private static string mConfigGenerateExeName = "ExcelToJson.exe";

        [MenuItem("FrameworkEditor/ConfigGenerate")]
        public static void ConfigGenerate()
        {
            mConfigGenerateFolderPath = ManagerCollection.DataManager.GetPlayerPrefs<string>(FrameworkDefine.ConfigGenerateFolderPathKey);
            EditorWindow.GetWindowWithRect<ConfigGenerateEditor>(new Rect(0, 0, 500, 100), false, "ConfigGenerate");
        }

        private void OnValidate()
        {
            mConfigGenerateFolderPath = ManagerCollection.DataManager.GetPlayerPrefs<string>(FrameworkDefine.ConfigGenerateFolderPathKey);
        }

        private void OnGUI()
        {
            GUIConfigFolder();
            GUIConfigGenerate();
        }

        private void GUIConfigFolder()
        {
            GUILayout.Label("配置目录：" + mConfigGenerateFolderPath);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("选择目录"))
            {
                string path = EditorUtility.OpenFolderPanel("选择目录", mConfigGenerateFolderPath, "");
                if (!string.IsNullOrEmpty(path))
                {
                    mConfigGenerateFolderPath = path + "/";
                    ManagerCollection.DataManager.SetPlayerPrefs<string>(FrameworkDefine.ConfigGenerateFolderPathKey, mConfigGenerateFolderPath);
                }
            }

            if (GUILayout.Button("打开目录"))
            {
                if (Directory.Exists(mConfigGenerateFolderPath))
                    EditorUtility.RevealInFinder(mConfigGenerateFolderPath);
                else
                    Debug.LogWarning("目录不存在");
            }

            if (GUILayout.Button("输出目录路径"))
            {
                Debug.Log("配置目录路径：" + mConfigGenerateFolderPath);
            }
            GUILayout.EndHorizontal();
        }

        private void GUIConfigGenerate()
        {
            GUILayout.Label("配置导出：");
            if (GUILayout.Button("配置导出"))
            {
                if (!Directory.Exists(mConfigGenerateFolderPath))
                {
                    Debug.LogWarning("目录不存在");
                    return;
                }

                string exePath = mConfigGenerateFolderPath + mConfigGenerateExeName;
                if (!File.Exists(exePath))
                {
                    Debug.LogWarning("导表程序不存在，路径：" + exePath);
                    return;
                }

                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = exePath;
                processStartInfo.WorkingDirectory = mConfigGenerateFolderPath;
                processStartInfo.UseShellExecute = false;
                processStartInfo.RedirectStandardOutput = true;

                using (Process process = Process.Start(processStartInfo))
                {
                    // 等待进程结束
                    process.WaitForExit();

                    string result = process.StandardOutput.ReadToEnd();
                    if (result.Contains("配表导出成功"))
                    {
                        Debug.Log(result);
                        CopyConfigToFramework();
                    }
                    else
                    {
                        Debug.LogWarning(result);
                    }
                }
            }
        }

        private void CopyConfigToFramework()
        {
            string sourcePath = string.Format("{0}{1}", mConfigGenerateFolderPath, mConfigGenerateClientFolderName);
            if (!Directory.Exists(sourcePath))
            {
                Debug.LogWarning("生成配置目录不存在，路径为：" + sourcePath);
                return;
            }

            string destPath = string.Format("{0}/{1}", Application.dataPath, FrameworkDefine.ConfigRootDirectoryPath);
            if (Directory.Exists(destPath))
            {
                string[] files = Directory.GetFiles(destPath);
                if (files.Length > 0)
                    Directory.Delete(destPath, true);
            }
            else
            {
                Directory.CreateDirectory(destPath);
            }

            CopyDirectory(sourcePath, destPath);

            AssetDatabase.Refresh();
        }

        private void CopyDirectory(string pSourcePath, string pDestPath)
        {
            Debug.Log(string.Format("srcDirPath:{0} \n destDirPath:{1}", pSourcePath, pDestPath));

            if (!Directory.Exists(pDestPath))
                Directory.CreateDirectory(pDestPath);

            string[] directories = Directory.GetDirectories(pSourcePath);
            foreach (string sourcePath in directories)
            {
                string destPath = sourcePath.Replace(pSourcePath, pDestPath);
                CopyDirectory(sourcePath, destPath);
            }

            string[] files = Directory.GetFiles(pSourcePath);
            foreach (string file in files)
            {
                string destFile = file.Replace(pSourcePath, pDestPath);
                File.Copy(file, destFile, true);
            }
        }
    }
}